<template>
  <div class="common-layout">
    <el-container>
      <el-aside width="200px" style="min-height: 100vh; background-color: rgb(22,46,86)">
        <div class="aside-head-info"
             style="width: 200px; height: 80px; align-items: center; justify-items: center; display: flex">
          <span
              style="color: #f9f9f9; display: flex; align-items: center; justify-content: center; width: 200px">欢迎您，食堂管理员</span>
        </div>
        <el-menu style="border: none" :default-active="currentUrl" router background-color="#162E56"
                 text-color="#f9f9f9">
          <el-menu-item index="/restaurant-manager/index">
            <template #title>
              <el-icon>
                <User/>
              </el-icon>
              用户首页
            </template>
          </el-menu-item>
          <el-menu-item index="/restaurant-manager/restaurant-info-maintain">
            <template #title>
              <el-icon>
                <DishDot/>
              </el-icon>
              餐厅信息
            </template>
          </el-menu-item>
          <el-menu-item index="/restaurant-manager/dishes-maintain">
            <template #title>
              <el-icon>
                <Edit/>
              </el-icon>
              菜品维护
            </template>
          </el-menu-item>
          <el-menu-item index="/restaurant-manager/report-reply">
            <template #title>
              <el-icon>
                <Warning/>
              </el-icon>
              投诉回复
            </template>
          </el-menu-item>
          <el-menu-item index="/restaurant-manager/remark-reply">
            <template #title>
              <el-icon>
                <Message/>
              </el-icon>
              评论回复
            </template>
          </el-menu-item>
          <el-menu-item index="/restaurant-manager/recommend-dish-publish">
            <template #title>
              <el-icon>
                <More/>
              </el-icon>
              新品发布
            </template>
          </el-menu-item>
          <el-menu-item index="/restaurant-manager/vote">
            <template #title>
              <el-icon>
                <Collection/>
              </el-icon>
              调查发布
            </template>
          </el-menu-item>
        </el-menu>
      </el-aside>
      <el-container>
        <el-header style="box-shadow: 2px 0 6px rgba(0, 21, 41, .36); display: flex; align-items: center; justify-content: space-between">
          <el-breadcrumb :separator-icon="ArrowRight">
            <el-breadcrumb-item v-for="item in route.matched" :to="{path: item.path}">{{item.meta.title}}</el-breadcrumb-item>

          </el-breadcrumb>
          <div class="avatar-container" style="align-items: center; display: flex; justify-content: flex-end">
            <el-dropdown style="display: flex; align-items: center; justify-content: flex-end" placement="bottom">
        <span class="el-dropdown-link"
              style="display: flex; align-items: center;">
          <el-avatar :size="24" :src="avatarSrc" style="margin: 0 5px"/>
          {{ '欢迎您，' + nickname }}
        </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item>个人中心</el-dropdown-item>
                  <el-dropdown-item>退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </el-header>
        <el-main>
          <div class="app-container">
<!--            查询表单-->
            <el-form :model="queryParams" ref="queryForm" size="default" :inline="true" label-width="68px">
              <el-form-item label="菜品名称" prop="dishName">
                <el-input
                    v-model="queryParams.dishName"
                    placeholder="请输入菜品名称"
                    clearable
                    @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item label="菜品菜系" prop="compLevel">
                <el-select v-model="queryParams.cuisine" placeholder="请选择菜品菜系" clearable>
                  <el-option
                      v-for="item in dict_cuisine"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" :icon="Search" size="default" @click="handleQuery">搜索</el-button>
                <el-button :icon="Refresh" size="default" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>
<!--            功能按键-->
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button
                    type="primary"
                    plain
                    :icon="Plus"
                    size="small"
                    @click="handleAdd"
                >新增
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                    type="success"
                    plain
                    :icon="Edit"
                    size="small"
                    :disabled="single"
                    @click="handleUpdate"
                >修改
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                    type="danger"
                    plain
                    :icon="Delete"
                    size="small"
                    :disabled="multiple"
                    @click="handleDelete"
                >删除
                </el-button>
              </el-col>
            </el-row>
<!--            数据表格-->
            <el-table v-loading="tableLoading" :data="tableProp" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="55" align="center"/>
              <el-table-column label="id" align="center" prop="dishId" v-if="false"/>
              <el-table-column label="菜品名称" align="center" prop="dishName"/>
              <el-table-column label="菜品图片" align="center">
                <template #default="scope">
                  <img :src="scope.row.picture" style="width: 150px; height: 50px" alt="暂无菜品图片"/>
                </template>
              </el-table-column>
              <el-table-column label="菜品菜系" align="center" prop="cuisine"/>
              <el-table-column label="菜品原价" align="center" prop="originalPrice"/>
              <el-table-column label="菜品折扣价" align="center" prop="salesPrice"/>
              <el-table-column label="菜品是否打折" align="center" prop="status"/>
              <el-table-column label="菜品是否首页展示" align="center" prop="isDisplay"/>
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                  <el-button
                      size="small"
                      type="text"
                      :icon="Edit"
                      @click="handleUpdate(scope.row)"
                  >修改
                  </el-button>
                  <el-button
                      size="small"
                      type="text"
                      :icon="Delete"
                      @click="handleDelete(scope.row)"
                  >删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

<!--            分页器组件-->
            <el-pagination
                v-show="total>0"
                :total="total"
                @change="handlePageChange"
            />

<!--            添加/修改菜品对话框-->
            <el-dialog :title="title" v-model="dialogVis" width="400px" append-to-body @close="cancelForm">
                <el-form :model="form" style="align-items: center" :rules="formRules" ref="ruleFormRef">
                  <el-form-item label="菜品名称" prop="dishName">
                    <el-input v-model="form.dishName" placeholder="请输入菜品名称" clearable/>
                  </el-form-item>
                  <el-form-item label="菜品图片">
                    <el-upload
                        ref="upload"
                        class="upload-demo"
                        :limit="1"
                        :on-exceed="handleExceed"
                        :auto-upload="false"
                        :on-change="handleFileContentChange"
                        :before-upload="checkFileValidity"
                    >
                      <template #trigger>
                        <el-button type="primary">选择图片</el-button>
                      </template>
                      <template #tip>
                        <div class="el-upload__tip text-red">
                          限制上传一张图片，过多上传将被替代
                        </div>
                      </template>
                    </el-upload>
                  </el-form-item>
                  <el-form-item label="菜品菜系" prop="cuisine">
                    <el-select v-model="form.cuisine" placeholder="请选择菜品菜系" clearable>
                      <el-option
                          v-for="item in dict_cuisine"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="菜品原价" prop="originalPrice">
                    <el-input v-model="form.originalPrice" placeholder="请输入菜品原价" clearable/>
                  </el-form-item>
                  <el-form-item label="是否打折" prop="status">
                    <el-select v-model="form.status" placeholder="请选择是否打折" clearable>
                      <el-option
                          v-for="item in dict_yes_no"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                  <el-form-item v-show="form.status==='1'" label="打折价格" prop="salesPrice">
                    <el-input v-model="form.salesPrice" placeholder="请输入打折价格" clearable/>
                  </el-form-item>
                  <el-form-item>
                    <el-button @click="submitForm(ruleFormRef)" type="primary">确认</el-button>
                    <el-button @click="cancelForm" type="primary">取消</el-button>
                  </el-form-item>
                </el-form>
            </el-dialog>
          </div>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup>
import {useRoute} from "vue-router";
import {ArrowRight} from "@element-plus/icons-vue";
import {dict_yes_no, dict_cuisine, isNumeric, generalValidatorJudgeIfEmpty} from "@/utils/common.js";
import {queryAllSatisfiedDishes, queryCertainDetailDish, addCertainDish, deleteCertainDishesByIds, updateCertainDish} from "@/web-api/resaurant-manager/dishes-maintain.js";
import {Plus, Edit, Delete} from "@element-plus/icons-vue";
import {ElMessage, ElMessageBox, genFileId} from "element-plus";
import {Refresh, Search} from "@element-plus/icons-vue";
import {getLocalStorage, KEY_RESTAURANT_ID} from "../../utils/localStorge.js";
let route = useRoute();

const handlePageChange = (pageNum, pageSize)=>{
  queryParams.pageNum = pageNum;
  queryParams.pageSize = pageSize;
  handleQuery();
}

// 记录当前食堂管理员属于哪个食堂
let diningHall = ref('');

// 记录当前路由
let currentUrl = ref()

// 记录当前登录用户昵称
let nickname = ref('核打击')

// 记录当前登录用户头像，后期应该要大改
let avatarSrc = ref('/src/assets/turkey.svg')

// 查询参数
let queryParams = reactive({
  // 同步分页器
  pageNum: 1,
  pageSize: 10,
  // 归属食堂id，读取出来的，不要让他们填
  // TODO 要读取食堂id
  restId: getLocalStorage(KEY_RESTAURANT_ID),
  // 可以用来查询的两个参数
  dishName: null,
  cuisine: null
})

// beforeMounted记得读取一下这个页面的管理员属于哪个食堂
let form = reactive({
  // 餐品id
  dishId: '',
  // 餐品名
  dishName: '',
  // 归属食堂id，读取出来的，不要让他们填
  restId: '',
  // 菜系
  cuisine: '',
  // 是否打折，选框
  status: '',
  // 原价
  originalPrice: '',
  // 打折价，如果不打折就不显示，判断是否高于原价
  salesPrice: '',
  // 是否作为首页展示菜品，记得判断要唯一
  // isDisplay: ''
})

// 如果上传食物图片，用这个保存
let foodPic = reactive({
  fileContent: null
})

// 当前页数据
let tableProp = ref([]);
// 当前页数据总数
let total = ref(0);
// 表格加载遮罩层
let tableLoading = ref(false);
// 选中的菜品id
let ids = ref([])

// 根据关键字查询
const handleQuery = ()=>{
  getList(queryParams);
}

// 查询整页数据
const getList = (queryParams)=>{
  console.log("queryParams")
  console.log(queryParams)
  tableLoading.value = true;
  let params = {restId: queryParams.restId, pageNum: queryParams.pageNum, pageSize: queryParams.pageSize,
    dishName: queryParams.dishName, cuisine: queryParams.cuisine}
  console.log(params)
  queryAllSatisfiedDishes(params).then(res=>{
    // 修改枚举为正常的显示效果
    tableProp.value = res.rows
    tableProp.value.map(item=>{
      item.status = item.status==='0'?'否':'是';
      item.isDisplay = item.status==='0'?'否':'是';
    });
    total.value = res.total;
    tableLoading.value = false;
  })
}

// 重置查询
const resetQuery = ()=>{
  queryParams = reactive({
    // 同步分页器
    pageNum: 1,
    pageSize: 10,
    // 归属食堂id，读取出来的，不要让他们填
    // TODO 读取食堂id
    restId: getLocalStorage(KEY_RESTAURANT_ID),
    // 可以用来查询的两个参数
    dishName: null,
    cuisine: null
  });
  handleQuery();
}

// 表格选中的项目
const handleSelectionChange =(selected)=>{
  ids.value = selected.map(item=>item.dishId);
  single.value = selected.length !== 1;
  multiple.value = !selected.length;
}

// 当选取超过一个时，禁用
let single = ref(true)

// 当选取个数为0时，禁用
let multiple = ref(true)

// 新增功能
const handleAdd = ()=>{
  resetAddOrUpdateForm();
  foodPic.fileContent = null;
  title.value = '新增菜品'
  dialogVis.value = true;
}

// 修改功能
const handleUpdate = (row)=>{
  let certainId = row.dishId || ids.value;
  resetAddOrUpdateForm();
  queryCertainDetailDish(certainId).then(res=>{
    // console.log(res)
    form.originalPrice = res.data.originalPrice;
    form.status = res.data.status==='1'?"是":'否';
    form.salesPrice = res.data.salesPrice;
    form.dishName = res.data.dishName;
    form.dishId = res.data.dishId;
    form.cuisine = res.data.cuisine;
    // restId都在提交之前给他绑定
    // form.restId = ''
  })
  foodPic.fileContent = null;
  title.value = '修改菜品'
  dialogVis.value = true;
}

// 删除功能
const handleDelete = (row)=>{
  let delIds = row.dishId?row.dishId:ids.value
  ElMessageBox.confirm('您确定要删除这些数据吗？', '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(()=>{
    deleteCertainDishesByIds(delIds).then(res=>{
      ElMessage.success("删除成功！");
      handleQuery();
    }).catch(err=>{
      console.log(err);
    })
  }).catch(()=>{
    ElMessage.info('删除取消！')
  })
}

// 重置form表单
function resetAddOrUpdateForm(){
  form = reactive({
    // 餐品id
    dishId: '',
    // 餐品名
    dishName: '',
    // 归属食堂id，读取出来的，不要让他们填
    restId: getLocalStorage(KEY_RESTAURANT_ID),
    // 菜系
    cuisine: '',
    // 是否打折，选框
    status: '',
    // 原价
    originalPrice: '',
    // 打折价，如果不打折就不显示，判断是否高于原价
    salesPrice: ''
  })
}

// 提交表单分为修改提交和新增提交
const submitForm = (formEl)=>{
  if (!formEl) return;
  formEl.validate(valid=>{
    if(!checkFileValidity(foodPic.fileContent)){
      return;
    }
    if(valid){
      let formData = new FormData()
      formData.append("dish", form);
      formData.append("dishPic", foodPic.fileContent)
      // TODO 获取归属餐馆id
      form.restId = getLocalStorage(KEY_RESTAURANT_ID)
      if(form.dishId!==''||form.dishId!==null){
        updateCertainDish(formData).then(res=>{
          ElMessage.success("修改成功！");
          dialogVis.value = false;
          handleQuery();
        })
      }else{
        addCertainDish(formData).then(res=>{
          ElMessage.success("新增成功！")
          dialogVis.value = false;
          handleQuery();
        })
      }
    }
  })
  // 提交后重置并刷新主页表格
  resetAddOrUpdateForm();
}

const cancelForm = ()=>{
  dialogVis.value = false;
  resetAddOrUpdateForm();
}

// 对话框标题
let title = ref("新增菜品");
// 对话框可见性
let dialogVis = ref(false)
// 表单引用
let ruleFormRef = ref()
// 自定义折扣价验证器
const salesPriceValidator = (rule, value, callback)=>{
  if (form.status==='1'&&(value===''||value===null)){
    callback(new Error("菜品促销价格不能为空！"))
  }else if(!isNumeric(value)){
    callback(new Error("菜品价格必须为数字！"))
  }else if(parseFloat(value)>parseFloat(form.originalPrice)){
    callback(new Error("菜品折扣价必须小于原价！"))
  }else{  callback();}
}
// 自定义原价验证器
const originalValidator = (rule, value, callback)=>{
  if(value===''||value===null){
    callback(new Error("菜品原价不能为空！"))
  }else if(!isNumeric(value)) {
    callback(new Error("菜品价格必须为数字！"))
  }else{
    callback()
  }
}

// 添加/修改对话框校验规则
let formRules = ref({
  dishName: [
    {validator: generalValidatorJudgeIfEmpty("菜品名称不能为空！"), trigger: 'blur'}
  ],
  salesPrice: [
    {validator: salesPriceValidator, trigger: 'blur'}
  ],
  cuisine: [
    {validator: generalValidatorJudgeIfEmpty('菜品菜系不能为空！'), trigger: 'blur'}
  ],
  status: [
    {validator: generalValidatorJudgeIfEmpty("是否打折不能为空！"), trigger: 'blur'},
  ],
  originalPrice: [
    {validator: originalValidator, trigger: 'blur'}
  ]
})

// 上传引用
let upload = ref()

// 当上传的图片超出数量限制时触发
const handleExceed = (files)=>{
  upload.value.clearFiles()
  const file = files[0]
  file.uid = genFileId()
  upload.value.handleStart(file)
}

// 文件上传前，检查是否是jpg或png文件，检查文件大小是否合法
const checkFileValidity = (rawFile)=>{
  if (!(rawFile.type in ['image/jpeg', 'image/png'])){
    ElMessage.error('上传的图片必须是.jpg或.png格式！')
    return false;
  }else if(rawFile.size/1024/1024>10){
    ElMessage.error('上传的图片大小超过10MB!')
    return false;
  }
  return true;
}

const handleFileContentChange = (ev)=>{
  console.log(ev.raw);
  if(!ev.raw){
    ElMessage.error("上传图片失败！");
    return;
  }
  foodPic.value.fileContent = ev.raw;
}

onMounted(() => {
  currentUrl.value = route.path;
  getList(queryParams);
})

onBeforeMount(()=>{

})

</script>

<style scoped>
.is-active {
  color: #f9f9f9 !important;
  background-color: #47739a;
  border-radius: 20px;
  margin: 0 10px;
}

.el-menu-item {
  margin: 5px 10px !important;
}

.el-menu-item:hover {
  border-radius: 20px;
}
::v-deep .el-form-item__content .el-input--suffix{
  width: 240px !important;
}
</style>